"use strict";

/**
 * Created by hehe on 2015/7/21.
 */
var Q = require('q'),
    Parser = require('parse-xl'),
    DaoFactory = require('../dao'),
    Parser = require('./parser'),
    nodeExcel = require('excel-export');

function OrderBiz() {
    this.orderDao = new DaoFactory.OrderDao();
    this.fileDao = new DaoFactory.FileDao();
}


OrderBiz.prototype.deleteOrder = function (orderID) {
    return this.orderDao.deleteOrder(orderID);
}

OrderBiz.prototype.deleteOrderByBatchID = function (batchID) {
    var self = this;
    var deleteOrderPromise = self.orderDao.deleteOrderByBatchID(batchID);
    deleteOrderPromise.then(
        function (data) {
            return self.fileDao.deleteFile(batchID);
        }
    )
    return deleteOrderPromise;
}


OrderBiz.prototype.getParser = function (parserType, option) {
    if (parserType == 1) {
        return new Parser.HandFilledParser({'filePath': option.filePath});
    } else if (parserType == 2) {
        return new Parser.XieChengParser({'filePath': option.filePath});
    }
}

OrderBiz.prototype.parseData = function (option) {
    var self = this, defferred = Q.defer(), errArray = new Array();
    var excelParser = self.getParser(option.parserType, {'filePath': option.filePath});
    var DDArray = excelParser.parseExcel();

    function execute(index) {
        function successCallBack(errs) {
            for (var i in errs) {
                errArray.push(errs[i]);
            }
            index++;
            if (index < DDArray.length) {
                execute(index);
            } else {
                defferred.resolve(errArray);
            }
        }

        var order = excelParser.parserToOrder(option.batchID, DDArray[index]);
        if (order == undefined) {
            successCallBack([DDArray[index]]);
        } else {
            var insertPromise = self.insertOrder(order);
            insertPromise.then(function (data) {
                successCallBack([]);
            }, function (err) {
                successCallBack([err]);
            });
        }
    }

    execute(0);
    return defferred.promise;
}

OrderBiz.prototype.insertOrder = function (order) {
    return this.orderDao.insertOrder(order);
}

OrderBiz.prototype.insertOrders = function (order) {
    var self = this, defferred = Q.defer(), callBackCount = 0, errArray = new Array();
    for (var i = 0, l = order.deviceQuantity; i < l; i++) {
        self.orderDao.insertOrder(order).then(function () {
            callBackCount++;
            if (callBackCount == l) {
                defferred.resolve(errArray);
            }
        }, function (err) {
            errArray.push(err);
            callBackCount++;
            if (callBackCount == l) {
                defferred.resolve(errArray);
            }
        });
    }
    return defferred.promise;
}

OrderBiz.prototype.excelInsertedIntoDB = function () {

    var self = this, defferred = Q.defer(), unCheckList, index = 0, totalError = new Array();

    var parseDataPromise = function (index) {
        if (index >= unCheckList.length) {
            defferred.resolve(totalError);
        } else {
            return self.parseData({parserType: unCheckList[index].FPARSERTYPE, batchID: unCheckList[index]._id, filePath: unCheckList[index].FFILERENAME});
        }
    }

    function successCallBack(errArray) {
        var batchID = unCheckList[index]._id;
        self.fileDao.updateCheckedOfFile(batchID, 1)
            .then(
            function () {
                totalError.push({batchID: batchID, dataError: errArray});
                self.fileDao.insertErrorMessage(batchID, JSON.stringify(errArray));
                parseDataPromise(++index).then(successCallBack);
            },
            function (err) {
                totalError.push({batchID: batchID, otherError: err, dataError: errArray});
                self.fileDao.insertErrorMessage(batchID, JSON.stringify({otherError: err, dataError: errArray}));
                parseDataPromise(++index).then(successCallBack);
            }
        );
    }

    self.fileDao.findUnCheckFileInfo().then(
        function (data) {
            unCheckList = data;
            parseDataPromise(index).then(successCallBack);
        }, defferred.reject);

    return defferred.promise;
}

OrderBiz.prototype.findOrderByConditions = function (option) {
    if (option.conditions.channelsOrderNo) {
        option.conditions.channelsOrderNo = new RegExp(option.conditions.channelsOrderNo);
    }
    if (option.conditions.sn) {
        option.conditions.sn = new RegExp(option.conditions.sn);
    }
    if (option.conditions.expressRecipientTel) {
        option.conditions.expressRecipientTel = new RegExp(option.conditions.expressRecipientTel);
    }
    if (option.conditions.receiveAddress) {
        option.conditions.receiveAddress = new RegExp(option.conditions.receiveAddress);
    }
    return this.orderDao.findOrderByConditions(option.conditions, option.pageInfo);
}

OrderBiz.prototype.exportExcel = function (option) {
    function dateFormat(row, cellData, eOpt) {
        var originDate = new Date(1899, 11, 30);
        if (cellData === null) {
            eOpt.cellType = 'string';
            return 'N/A';
        } else {
            return (new Date(cellData) - originDate) / (24 * 60 * 60 * 1000);
        }
    }

    var defferred = Q.defer();
    var conf = {};
    conf.stylesXmlFile = "styles.xml";
    conf.cols = [
        {
           caption: '出库时间',
            type: 'date',
            width: 14.7109375,
            beforeCellWrite: dateFormat
        },
        {
            caption: 'SN',
            type: 'string',
            width: 14.7109375
        },
        {
            caption: '是否还机入库',
            type: 'string',
            width: 14.7109375
        },
        {
            caption: '渠道订单号',
            type: 'string',
            width: 14.7109375
        },
        {
            caption: '下单时间',
            type: 'date',
            width: 14.7109375,
            beforeCellWrite: dateFormat
        },
        {
            caption: '渠道公司名',
            type: 'string',
            width: 14.7109375
        },
        {
            caption: '押金状态',
            type: 'string',
            width: 14.7109375
        },
        {
            caption: '租借地点',
            type: 'string',
            width: 28.7109375
        },
        {
            caption: '返还地点',
            type: 'string',
            width: 28.7109375
        },
        {
            caption: '联系电话',
            type: 'string',
            width: 14.7109375
        },
        {
            caption: '联系人',
            type: 'string',
            width: 14.7109375
        },
        {
            caption: '租借天数',
            type: 'string',
            width: 14.7109375
        },
        {
            caption: '备注1',
            type: 'string',
            width: 14.7109375
        },
        {
            caption: '备注2',
            type: 'string',
            width: 14.7109375
        },
        {
            caption: '出境时间',
            type: 'date',
            width: 14.7109375,
            beforeCellWrite: dateFormat
        },
        {
            caption: '入境时间',
            type: 'date',
            width: 14.7109375,
            beforeCellWrite: dateFormat
        }
    ];
    conf.rows = [];

    this.orderDao.findOrderByConditions(option.conditions, option.pageInfo).then(function (dataList) {
        for (var i in dataList) {
            var order = dataList[i];
            if(order.FDEVICELIST == undefined) continue;
            for (var k = 0;k < order.FDEVICELIST.length; k++) {
                var row = new Array();
                row.push(order.FDEVICELIST[k].FEXWAREHOUSETIME);
                row.push(order.FDEVICELIST[k].FSN);
                if (order.FDEVICELIST[k].FINWAREHOUSETIME) {
                    row.push('已还机');
                } else {
                    row.push('未还机');
                }
                row.push(order.FCHANNELSORDERNO || '');
                row.push(order.FPLACEORDERTIME || '');
                row.push(order.FCHANNELCOMPAYNAME || '');
                row.push(order.FFOREGIFTSTATUS || '');
                row.push(order.FRECEIVEADDRESS || '');
                row.push(order.FRESTITUTIONADDRESS || '');
                row.push(order.FEXPRESSRECIPIENTTEL || '');
                row.push(order.FEXPRESSRECIPIENT || '');
                row.push(order.FLEASEDAYNUMBER || '');
                row.push(order.FORDERREAMK1 || '');
                row.push(order.FORDERREAMK2 || '');
                row.push(order.FLEASEBEGINTIME || '');
                row.push(order.FLEASEENDTIME || '');
                conf.rows.push(row);
            }
        }

        var result = nodeExcel.execute(conf);
        defferred.resolve(result);
    }, defferred.reject);
    return defferred.promise;
}

OrderBiz.prototype.doubleChecked = function (bachID) {
    var self = this, defferred = Q.defer();
    var autditPromise = self.orderDao.auditOrder(bachID)
        .then(function (data) {
            return self.fileDao.updateCheckedOfFile(bachID, 2);
        }, defferred.reject);
    autditPromise.then(defferred.resolve,defferred.reject)
    return defferred.promise;
}

OrderBiz.prototype.updateOrder = function (order) {
    return this.orderDao.updateOrderTemp(order);
}

OrderBiz.prototype.exWareHouse = function (order) {
    for (var i in order.FDEVICELIST) {
        order.FDEVICELIST[i].FEXWAREHOUSETIME = order.FDEVICELIST[i].FEXWAREHOUSETIME || new Date();
    }
    ;
    return this.orderDao.updateOrder(order);
}

OrderBiz.prototype.inWareHouse = function (order) {
    for (var i in order.FDEVICELIST) {
        order.FDEVICELIST[i].FINWAREHOUSETIME = order.FDEVICELIST[i].FINWAREHOUSETIME || new Date();
    }
    ;
    return this.orderDao.updateOrder(order);
}

OrderBiz.prototype.findOrderInfoByOrderID = function (orderID) {
    return this.orderDao.findOrderInfoByOrderID(orderID);
}

exports.OrderBiz = OrderBiz;


//new OrderBiz().parseData({batchID:'aaa',filePath:'aaa.xlsx'});
//new OrderBiz().excelInsertedIntoDB().then(function (data) {
//    console.log('-------end-------' + JSON.stringify(data));
//}, function (err) {
//    console.log('-------enderr-------' + err);
//});

//new OrderBiz().findOrderByConditions({conditions:{'sn':new RegExp("111")},pageInfo:{pageSize:10,startAt:0}})
//    .then(function(data){console.log(data)});

//new OrderBiz().findOrderByConditions({conditions:{batchID:'55b077b20917f2300d3abc95',expressRecipient:'陆丽珍'},pageInfo:{pageSize:10,startAt:0}})
//    .then(function(data){console.log(data)});